// 错误处理和日志系统
export class ErrorHandler {
  static logs: Array<{ timestamp, level, message, data?: any }> = []
  static maxLogs = 1000
  static isInitialized = false

  // 初始化错误处理系统
  static init() {
    if (this.isInitialized) return
    
    // 捕获未处理的错误
    window.addEventListener('error', (event) => {
      this.logError('Uncaught Error', {
        message: event.message,
        filename: event.filename,
        lineno: event.lineno,
        colno: event.colno,
        error: event.error?.stack
      })
    })

    // 捕获未处理的Promise拒绝
    window.addEventListener('unhandledrejection', (event) => {
      this.logError('Unhandled Promise Rejection', {
        reason: event.reason,
        promise: event.promise
      })
    })

    // 捕获Phaser错误（如果可用）
    if (typeof Phaser !== 'undefined') {
      const originalError = console.error
      console.error = (...args) => {
        if (args[0] && typeof args[0] === 'string' && args[0].includes('Phaser')) {
          this.logError('Phaser Error', args)
        }
        originalError.apply(console, args)
      }
    }

    this.isInitialized = true
    this.logInfo('ErrorHandler initialized')
  }

  // 记录信息日志
  static logInfo(message, data?) {
    this.addLog('INFO', message, data)
    console.log(`[INFO] ${message}`, data || '')
  }

  // 记录警告日志
  static logWarning(message, data?) {
    this.addLog('WARNING', message, data)
    console.warn(`[WARNING] ${message}`, data || '')
  }

  // 记录错误日志
  static logError(message, data?) {
    this.addLog('ERROR', message, data)
    console.error(`[ERROR] ${message}`, data || '')
  }

  // 记录调试日志
  static logDebug(message, data?) {
    this.addLog('DEBUG', message, data)
    if (process.env.NODE_ENV === 'development') {
      console.debug(`[DEBUG] ${message}`, data || '')
    }
  }

  // 添加日志条目
  static addLog(level, message, data?) {
    this.logs.push({
      timestamp: new Date(),
      level,
      message,
      data
    })

    // 限制日志数量
    if (this.logs.length > this.maxLogs) {
      this.logs = this.logs.slice(-this.maxLogs)
    }
  }

  // 获取所有日志
  static getLogs(): Array<{ timestamp, level, message, data?: any }> {
    return [...this.logs]
  }

  // 获取特定级别的日志
  static getLogsByLevel(level): Array<{ timestamp, level, message, data?: any }> {
    return this.logs.filter(log => log.level === level)
  }

  // 清空日志
  static clearLogs() {
    this.logs = []
    this.logInfo('Logs cleared')
  }

  // 导出日志为文本
  static exportLogs(): string {
    return this.logs.map(log => {
      const timestamp = log.timestamp.toISOString()
      const data = log.data ? ` | Data: ${JSON.stringify(log.data)}` : ''
      return `[${timestamp}] [${log.level}] ${log.message}${data}`
    }).join('\n')
  }

  // 安全执行函数（捕获并记录错误）
  static safeExecute<T>(
    fn: () => T,
    errorMessage= 'Function execution failed',
    defaultValue?): T | undefined {
    try {
      return fn()
    } catch (error) {
      this.logError(errorMessage, {
        error: error instanceof Error ? error.message ,
        stack: error instanceof Error ? error.stack : undefined
      })
      return defaultValue
    }
  }

  // 安全执行异步函数
  static async safeExecuteAsync<T>(
    fn: () => Promise<T>,
    errorMessage= 'Async function execution failed',
    defaultValue?): Promise<T | undefined> {
    try {
      return await fn()
    } catch (error) {
      this.logError(errorMessage, {
        error: error instanceof Error ? error.message ,
        stack: error instanceof Error ? error.stack : undefined
      })
      return defaultValue
    }
  }

  // 创建错误边界装饰器
  static createErrorBoundary(errorMessage) {
    return function(target, propertyName, descriptor) {
      const method = descriptor.value
      
      descriptor.value = function(...args) {
        return ErrorHandler.safeExecute(
          () => method.apply(this, args),
          `${errorMessage} in ${target.constructor.name}.${propertyName}`
        )
      }
    }
  }

  // 验证游戏状态
  static validateGameState(scene: Phaser.Scene): boolean {
    const issues= []

    // 检查场景状态
    if (!scene.scene.isActive()) {
      issues.push('Scene is not active')
    }

    // 检查关键游戏对象
    if (!scene.children || scene.children.length === 0) {
      issues.push('No game objects found in scene')
    }

    // 检查输入系统
    if (!scene.input) {
      issues.push('Input system not available')
    }

    // 检查时间系统
    if (!scene.time) {
      issues.push('Time system not available')
    }

    if (issues.length > 0) {
      this.logWarning('Game state validation failed', { issues })
      return false
    }

    return true
  }

  // 生成错误报告
  static generateErrorReport(): string {
    const errors = this.getLogsByLevel('ERROR')
    const warnings = this.getLogsByLevel('WARNING')
    
    const report = `
错误报告 - ${new Date().toISOString()}
=====================================

系统信息:
- 用户代理: ${navigator.userAgent}
- 屏幕分辨率: ${screen.width}x${screen.height}
- 可用内存: ${(navigator as any).deviceMemory || '未知'}GB
- 硬件并发: ${navigator.hardwareConcurrency || '未知'}

错误统计:
- 错误数量: ${errors.length}
- 警告数量: ${warnings.length}
- 总日志数量: ${this.logs.length}

最近的错误:
${errors.slice(-5).map(log => 
  `[${log.timestamp.toISOString()}] ${log.message}\n${log.data ? JSON.stringify(log.data, null, 2) : ''}`
).join('\n\n')}

最近的警告:
${warnings.slice(-5).map(log => 
  `[${log.timestamp.toISOString()}] ${log.message}\n${log.data ? JSON.stringify(log.data, null, 2) : ''}`
).join('\n\n')}
    `.trim()

    return report
  }

  // 保存错误报告到本地存储
  static saveErrorReport(): boolean {
    try {
      const report = this.generateErrorReport()
      localStorage.setItem('stardigits_error_report', report)
      localStorage.setItem('stardigits_error_report_timestamp', new Date().toISOString())
      this.logInfo('Error report saved to localStorage')
      return true
    } catch (error) {
      this.logError('Failed to save error report', error)
      return false
    }
  }

  // 从本地存储加载错误报告
  static loadErrorReport(): string | null {
    try {
      return localStorage.getItem('stardigits_error_report')
    } catch (error) {
      this.logError('Failed to load error report', error)
      return null
    }
  }
}
